<?php

namespace app\api\service;

use addons\xyb\XypHelper;

use app\common\model\dynamic\Activity as ActivityModel;
use \app\common\model\dynamic\Progress as progressModel;
use \app\common\model\dynamic\Jobs as jobsModel;
use app\common\model\daily\UsersModel;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\marketing\UsersMarketingCoupons;
use app\common\model\publics\Huati;
use think\Db;
use think\Log;

class DynamicService
{

    public static function retrieveUsersOngoingTasksParticipation($user_id, $circle_id = 0){
        // 定义需要查询的字段
        $field = 'id,name,cover,banner,slogan as sub_title,describe,grant_total,grant_status,end_time,start_time';
        // 初始化查询对象
        $query = ActivityModel::field($field)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });

        // 执行查询并分页
        $activity = $query->order('id', 'desc')->paginate();
        if(!$activity->count()){
            return [];
        }
        foreach ($activity as $key => $value){
            $value->cover = cdnurl($value->cover);
            $value->grant_status = 1;
        }
        return $activity;
    }
    /*查询用户可参与的*/
    public static function retrieveUsersOngoingTasksDetails($activity_id, $user_id, $circle_id = 0)
    {
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time,talk_id';
        $progress = progressModel::field($field)->where('user_id', $user_id)
            ->where('progress_type', 1)->where('activity_id', $activity_id)
            ->order('id', 'desc')->find();
        if (!$progress) {
            /*获取用户可参加的活动*/
            return self::retrieveUsersFirstParticipateActivityDetails($activity_id, $user_id, $circle_id);
        }
        /*获取活动详情*/
        if (!$activity = self::getUsersParticipateActivity($progress->activity_id, $user_id, $circle_id)) {
            return self::retrieveUsersFirstParticipateActivityDetails($activity_id,$user_id, $circle_id);
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return self::retrieveUsersFirstParticipateActivityDetails($activity_id,$user_id, $circle_id);
        }

        $activity->activity_status = 1;
        $activity->next_jobs_id = 0;
        $activity->self_reward = [];
        $activity->inviter_reward = [];

        /*进行中*/
        if ($progress->grant_status == 1) {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        } /*已完成*/
        elseif ($progress->grant_status == 2) {
            if ($activity->upgrade == 2) {
                if ($next_jobs = jobsModel::getNextJobsInfoByActivity($progress->activity_id, $progress->jobs_id)) {
                    $activity->next_jobs_id = $next_jobs->id;
                }
                $activity->activity_status = 2;
            } else {
                $activity->activity_status = 0;
            }
        } elseif ($progress->grant_status == 3) {
            if ($activity->is_restart == 1) {
                $activity->activity_status = 0;
            }
        } else {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        }
        /*邀请人奖励*/
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        /*被邀请人奖励*/
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];

        $activity->talk_lists = [];
        $activity->push_num = 0;
        $activity->complete_num = 0;
        /*动态已完成话题*/
        $progress_talk_ids = [];
        if($jobs->dynamic_status == 1){
            if(isset($progress->talk_id) && $progress->talk_id){
                $progress_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id);
            }
            $activity->talk_lists = self::getTalkLists($jobs->talk_id, $jobs, $progress);
            $activity->push_num = (int)$jobs->push_num;
            $activity->complete_num = count($progress_talk_ids);
        }
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = $activity->activity_status;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->deadline_time = (int)(($progress->deadline_time - time()));
        $activity->progress_id = $progress->id;
        $activity->invitation_status = (int)$jobs->invitation_status;
        $activity->share_img = cdnurl($activity->share_img);
        $activity->cover = cdnurl($activity->cover);
        /*获取参与人数*/
        $activity->help_users_list = [];
        if($activity->grant_total){
            $activity->help_users_list = progressModel::getParticipateUsersList($progress->id, $activity->grant_total);
        }
        $activity->help_users_total = progressModel::where('progress_id', $progress->id)->where('progress_type',2)->count();

        return $activity;
    }

    /*查询用户可参与的*/
    public static function retrieveUsersOngoingTasks($user_id, $circle_id = 0)
    {
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time,talk_id';
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->order('id', 'desc')->find();
        if (!$progress) {
            /*获取用户可参加的活动*/
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }
        /*获取活动详情*/
        if (!$activity = self::getUsersParticipateActivity($progress->activity_id, $user_id, $circle_id)) {
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return self::retrieveUsersFirstParticipateActivity($user_id, $circle_id);
        }

        $activity->activity_status = 1;
        $activity->next_jobs_id = 0;
        $activity->self_reward = [];
        $activity->inviter_reward = [];

        /*进行中*/
        if ($progress->grant_status == 1) {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        } /*已完成*/
        elseif ($progress->grant_status == 2) {
            if ($activity->upgrade == 2) {
                if ($next_jobs = jobsModel::getNextJobsInfoByActivity($progress->activity_id, $progress->jobs_id)) {
                    $activity->next_jobs_id = $next_jobs->id;
                }
                $activity->activity_status = 2;
            } else {
                $activity->activity_status = 0;
            }
        } elseif ($progress->grant_status == 3) {
            if ($activity->is_restart == 1) {
                $activity->activity_status = 0;
            }
        } else {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        }
        /*邀请人奖励*/
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        /*被邀请人奖励*/
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];

        $activity->talk_lists = [];
        $activity->push_num = 0;
        $activity->complete_num = 0;
        /*动态已完成话题*/
        $progress_talk_ids = [];
        if($jobs->dynamic_status == 1){
            if(isset($progress->talk_id) && $progress->talk_id){
                $progress_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id);
            }
            $activity->talk_lists = self::getTalkLists($jobs->talk_id, $jobs, $progress);
            $activity->push_num = (int)$jobs->push_num;
            $activity->complete_num = count($progress_talk_ids);
        }
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = $activity->activity_status;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->deadline_time = (int)(($progress->deadline_time - time()));
        $activity->progress_id = $progress->id;
        $activity->invitation_status = (int)$jobs->invitation_status;
        $activity->share_img = cdnurl($activity->share_img);
        $activity->cover = cdnurl($activity->cover);
        /*获取参与人数*/
        $activity->help_users_list = [];
        if($activity->grant_total){
            $activity->help_users_list = progressModel::getParticipateUsersList($progress->id, $activity->grant_total);
        }
        $activity->help_users_total = progressModel::where('progress_id', $progress->id)->where('progress_type',2)->count();

        return $activity;
    }

    /*邀请人活动详情*/
    public static function retrieveInviteUsersOngoingTasks($user_id, $progress_id = 0){
        if(!$progress_id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        /*获取进度数据*/
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 2)->find();
        if(!$progress){
            return ['code' => 0, 'msg' => '您未助力，无法做任务'];
        }
        /*获取活动详情*/
        if (!$activity = ActivityModel::getActivityInfo($progress->activity_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        $activity->activity_status = 1;
        $activity->activity_id = $activity->id;
        $activity->self_reward = [];
        $activity->inviter_reward = [];
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $progress_talk_ids = [];
        if(isset($progress->talk_id) && $progress->talk_id){
            $progress_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id);
        }
        /*进行中*/
        if ($progress->grant_status == 1) {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        } else {
            if ((time() > $progress->deadline_time)) {
                $activity->activity_status = 3;
            }
        }
        $activity->grant_status = $activity->activity_status;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->deadline_time = (int)(($progress->deadline_time - time()));
        $activity->progress_id = $progress->id;
        $activity->talk_lists = self::getInviteTalkLists($jobs->talk_id, $jobs, $progress);
        $activity->push_num = (int)$jobs->fu_task_num;
        $activity->complete_num = count($progress_talk_ids);
        return $activity;
    }

    /*用户参与活动报名*/
    public static function userRegistrationParticipate($user_id, $circle_id, $jobs_id)
    {
        if (!$jobs = jobsModel::getJobsInfo($jobs_id)) {
            return ['code' => 0, 'msg' => '任务不存在'];
        }
        /*获取活动详情*/
        if (!$activity = self::getUsersParticipateActivity($jobs->activity_id, $user_id, $circle_id)) {
            return ['code' => 0, 'msg' => '无法参与活动'];
        }
        /*查询用户是否有在进行中的任务*/
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time';
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->order('id', 'desc')->find();
        if (!$progress) {
            $res = progressModel::userRegistrationParticipate($user_id, $jobs);
            if (!$res || !isset($res->id) || !$res->id) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
            }
            jobsModel::where('id', $jobs_id)->setInc('total_users');
            jobsModel::where('id', $jobs_id)->setInc('progress_total');
            return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
        }
        if ((int)$progress->grant_status === 1 && (int)$progress->deadline_time > time()) {
            return ['code' => 0, 'msg' => '您有正在进行中的任务，请先完成再参与'];
        }
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)
            ->where('activity_id', $jobs->activity_id)->order('id', 'desc')->find();
        if (!$progress) {
            $res = progressModel::userRegistrationParticipate($user_id, $jobs);
            if (!$res || !isset($res->id) || !$res->id) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
            }
            jobsModel::where('id', $jobs_id)->setInc('total_users');
            jobsModel::where('id', $jobs_id)->setInc('progress_total');
            return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
        }
        if ((int)$progress->grant_status === 1) {
            return ['code' => 0, 'msg' => '您有正在进行中的任务，请先完成再参与'];
        }
        if ((int)$progress->grant_status === 2) {
            if ($activity->upgrade == 2) {
                if (!$next_jobs = jobsModel::getNextJobsInfoByActivity($progress->activity_id, $progress->jobs_id)) {
                    return ['code' => 0, 'msg' => '无法参与活动'];
                }
                if($next_jobs->id  != $jobs->id){
                    return ['code' => 0, 'msg' => '您已完成任务，请先完成再参与'];
                }
                $res = progressModel::userRegistrationParticipate($user_id, $jobs);
                if (!$res || !isset($res->id) || !$res->id) {
                    return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
                }
                jobsModel::where('id', $jobs_id)->setInc('total_users');
                jobsModel::where('id', $jobs_id)->setInc('progress_total');
                return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
            } else {
                return ['code' => 0, 'msg' => '您已完成任务，不可重复参加'];
            }
        }
        if ((int)$progress->grant_status === 3) {
            if ($activity->is_restart == 2) {
                $res = progressModel::userRegistrationParticipate($user_id, $jobs);
                if (!$res || !isset($res->id) || !$res->id) {
                    return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
                }
                jobsModel::where('id', $jobs_id)->setInc('total_users');
                jobsModel::where('id', $jobs_id)->setInc('progress_total');
                return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
            }
        }

        return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
    }

    /*被邀请人点击邀请页码，显示助力详情*/
    public static function invitePeopleAssistDetails($progress_id){
        /*获取进度数据*/
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 1)->find();
        if(!$progress){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }

        /*获取任务详情*/
        if (!$activity = ActivityModel::getActivityInfo($jobs->activity_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        $activity->fu_task_status = $jobs->fu_task_status;
        $activity->fu_task_num = $jobs->fu_task_num;
        $activity->activity_id = $activity->id;

        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id),
            'status' => $jobs->fu_task_status == 1 ? '去领取' : '去参与',
            'push_num' => (int)$jobs->fu_task_num
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];

        return ['code' => 1, 'msg' => 'success', 'data' => $activity];
    }

    /*邀请人扫码助力*/
    public static function invitePeopleAssist($user_id, $progress_id){
        /*获取进度数据*/
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 1)->find();
        if($progress->deadline_time < time()){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($progress->grant_status == 2){
            return ['code' => 0, 'msg' => '任务已完成，无法助力'];
        }
        if($progress->grant_status == 3){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
//        if($progress->user_id == $user_id){
//            return ['code' => 0, 'msg' => '不能助力自己'];
//        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*获取任务详情*/
        if (!$activity = ActivityModel::getActivityInfo($progress->activity_id)) {
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->start_time > time() || $activity->end_time < time()){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->grant_status > 2){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        if($activity->grant_status == 2 && $activity->status_start_time){
            if($activity->status_start_time > time()){
                return ['code' => 0, 'msg' => '任务未开始，无法助力'];
            }
        }
//        $res = progressModel::where('progress_id', $progress_id)->where('user_id', $user_id)
//            ->where('progress_type', 2)->find();
//        if($res){
//            return ['code' => 0, 'msg' => '您已助力过了，无法重复助力'];
//        }
        if($jobs->invitation_status == 1 && $jobs->grant_total < 1){
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }
        /*参与用户类型；2=新用户*/
        if($jobs->invitation_status == 1 && $jobs->users_method == 2){
            if(!UsersModel::where('id', $user_id)->where('create_time', '>', (time() - 120))->find()){
                if(progressModel::where('user_id', $user_id)->find()){
                    return ['code' => 0, 'msg' => '您不是新用户，无法助力'];
                }
            }
        }
        Db::startTrans();
        /*创建进度表*/
        if(!$self_progress = progressModel::userPeopleRegistrationParticipate($user_id, $progress, $jobs->fu_task_status)){
            DB::rollback();
            return ['code' => 0, 'msg' => '任务已结束，无法助力'];
        }

        $dynamic_status = true;
        $invitation_status = true;
        if($jobs->dynamic_status == 1){
            $push_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id,'',[]);
            $dynamic_status = ((count($push_talk_ids) >= $jobs->push_num));
        }
        if($jobs->invitation_status == 1){
            $progress_total = progressModel::where('progress_id', $progress->id)->where('progress_type',2)->count();
            $invitation_status = ($progress_total >= $jobs->grant_total);
        }

        if($dynamic_status && $invitation_status && $jobs->examine_method == 1) {
            if(!self::distributeRewardsSelf($progress->user_id, $jobs)){
                DB::rollback();
                return ['code' => 0, 'msg' => '任务已结束，无法助力'];
            }
            progressModel::setProgressCompletion($progress_id);
        }

        /*被邀请人领取优惠劵*/
        if($jobs->fu_reward_method > 0 && $jobs->fu_task_status == 2){
            if(!self::distributeRewardsInviter($user_id, $jobs)){
                DB::rollback();
                return ['code' => 0, 'msg' => '任务已结束，无法助力'];
            }
        }
        Db::commit();
        $inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id),
            'fu_task_status' => (int)$jobs->fu_task_status,
            'push_num' => (int)$jobs->fu_task_num
        ];
        return  ['code' => 1, 'msg' => '助力成功, 您获得以下优惠卷', 'data' =>[
            'user_id'           => $progress->user_id,
            'progress_id'       => $progress_id,
            'activity_id'       => $progress->activity_id,
            'self_progress_id'  => (int)$self_progress->id,
            'self_reward'   => [
                'type' => $jobs->reward_method,
                'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
                'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
                'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
            ],
            'inviter_reward' => $inviter_reward
        ]];
    }


    /*获取用户可参与的活动;首次进入页面*/
    public static function retrieveUsersFirstParticipateActivityDetails($activity_id, $user_id, $circle_id = 0)
    {
        // 定义需要查询的字段
        $field = 'id,name,banner,slogan as sub_title,describe,guide,restart,upgrade,grant_status,share_img,share_title';
        // 初始化查询对象
        $query = ActivityModel::field($field)->where('id', $activity_id)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });

        $query->where('start_time', '<', time())->where('end_time', '>', time());
        // 执行查询并分页
        $activity = $query->order('id', 'desc')->find();
        if(!$activity){
            return [];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfoByActivity($activity->id)) {
            return [];
        }
        $activity->deadline_time = 0;
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $activity->activity_status = 1;
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = 0;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->progress_id = 0;
        $activity->share_img = cdnurl($activity->share_img);
        $activity->talk_lists = [];
        $activity->push_num = (int)($jobs->push_num);
        $activity->complete_num = 0;
        $help_users_list = [];
        if($activity->grant_total > 0 && $jobs->invitation_status == 1){
            for ($i = 0; $i < $activity->grant_total; $i++) {
                $help_users_list[$i] = ['user_id' => 0, 'nickname' => '', 'avatar' => ''];
            }
        }
        $activity->help_users_list = $help_users_list;
        if($jobs->dynamic_status == 1 && $jobs->talk_id){
            $activity->talk_lists = self::getTalkLists($jobs->talk_id, $jobs);
        }
        return $activity;
    }
    /*获取用户可参与的活动;首次进入页面*/
    public static function retrieveUsersFirstParticipateActivity($user_id, $circle_id = 0)
    {
        // 定义需要查询的字段
        $field = 'id,name,banner,slogan as sub_title,describe,guide,restart,upgrade,grant_status,share_img,share_title';
        // 初始化查询对象
        $query = ActivityModel::field($field)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });

        $query->where('start_time', '<', time())->where('end_time', '>', time());
        // 执行查询并分页
        $activity = $query->order('id', 'desc')->find();
        if(!$activity){
            return [];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfoByActivity($activity->id)) {
            return [];
        }
        $activity->deadline_time = 0;
        $activity->self_reward = [
            'type' => $jobs->reward_method,
            'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
            'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
        ];
        $activity->inviter_reward = [
            'type' => $jobs->fu_reward_method,
            'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
            'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
            'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
        ];
        $activity->activity_status = 1;
        $activity->is_restart = (int)$activity->restart;
        $activity->is_upgrade = (int)$activity->upgrade;
        $activity->grant_status = 0;
        $activity->current_jobs_id = (int)$jobs->id;
        $activity->grant_total = (int)$jobs->grant_total;
        $activity->days_num = (int)$jobs->days_num;
        $activity->users_method = (int)$jobs->users_method;
        $activity->progress_id = 0;
        $activity->share_img = cdnurl($activity->share_img);
        $activity->talk_lists = [];
        $activity->push_num = (int)($jobs->push_num);
        $activity->complete_num = 0;
        $help_users_list = [];
        if($activity->grant_total > 0 && $jobs->invitation_status == 1){
            for ($i = 0; $i < $activity->grant_total; $i++) {
                $help_users_list[$i] = ['user_id' => 0, 'nickname' => '', 'avatar' => ''];
            }
        }
        $activity->help_users_list = $help_users_list;
        if($jobs->dynamic_status == 1 && $jobs->talk_id){
            $activity->talk_lists = self::getTalkLists($jobs->talk_id, $jobs);
        }
        return $activity;
    }

    /*获取用户可参与的活动*/
    public static function retrieveUsersParticipateActivity($user_id, $circle_id = 0)
    {
        // 定义需要查询的字段
        $field = 'id,name,banner,describe,guide,start_time,end_time,grant_method,grant_agent_id,grant_users_id,
        restart,upgrade,grant_status,status_start_time';

        // 初始化查询对象
        $query = ActivityModel::field($field)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });

        $query->where('start_time', '<', time())->where('end_time', '>', time());
        // 执行查询并分页
        $activity = $query->order('id', 'desc')->find();
        return $activity;
    }

    /*获取用户当前活动是否可参加*/
    public static function getUsersParticipateActivity($activity_id, $user_id, $circle_id)
    {
        // 定义需要查询的字段
        $field = 'id,name,slogan as sub_title,banner,describe,guide,start_time,end_time,grant_method,grant_agent_id,grant_users_id,
        restart,upgrade,grant_status,status_start_time,share_title,share_img,cover';

        // 初始化查询对象
        $query = ActivityModel::field($field)->where('id', $activity_id)->where(function ($query) {
            $query->where('status', 1)->whereOr(function ($query) {
                $query->where('status', 2)->where('status_start_time', '<', time());
            });
        });
        // 构建复杂的查询条件，包括社团的授权方式和用户、圈子的关系
        $query->where(function ($query) use ($user_id, $circle_id) {
            $query->where('grant_method', 1);
            if($circle_id){
                $query->whereOr(function ($q) use ($circle_id, $user_id) {
                    $q->whereOr(function ($q) use ($circle_id) {
                        $q->where("grant_method", 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                });
            } else {
                $query->whereOr(function ($q) use ($user_id) {
                    $q->where("grant_method", 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                });
            }
        });

        $query->where('start_time', '<', time())->where('end_time', '>', time());
        return $query->order('id', 'desc')->find();
    }

    /*发放被邀请人奖励*/
    public static function distributeRewardsInviter($user_id, $jobs)
    {
        if($jobs->fu_reward_method < 1){
            return true;
        }
        switch ($jobs->fu_reward_method){
            case 1:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->fu_reward_point, 'score', '助力获取');
                break;
            case 2:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->fu_youth_point, 'youth_coin', '助力获取');
                break;
            case 3:
                if(!$reward_coupons_id = XypHelper::formatJsonStringToArray($jobs->fu_reward_coupons_id)){
                    return false;
                }
                foreach ($reward_coupons_id as $value){
                    $field = 'id,expiration_method,use_end_time,effective_days,type';
                    $coupon = MarketingCoupons::field($field)->where('id', $value['id'])->find();
                    UsersMarketingCoupons::usersJobsReceiveCoupons($user_id, $coupon,2);
                }
                break;
        }
        return true;
    }

    /*发放邀请人奖励*/
    public static function distributeRewardsSelf($user_id, $jobs)
    {
        if(!$jobs->reward_method){
            return true;
        }
        switch ($jobs->reward_method){
            case 1:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->reward_point, 'score', '助力获取');
                break;
            case 2:
                UsersModel::increaseUserCurrency($user_id, (int)$jobs->youth_point, 'youth_coin', '助力获取');
                break;
            case 3:
                if(!$reward_coupons_id = XypHelper::formatJsonStringToArray($jobs->reward_coupons_id)){
                    return false;
                }
                foreach ($reward_coupons_id as $value){
                    $field = 'id,expiration_method,use_end_time,effective_days,type';
                    $coupon = MarketingCoupons::field($field)->where('id', $value['id'])->find();
                    UsersMarketingCoupons::usersJobsReceiveCoupons($user_id, $coupon,2);
                }
                break;
        }
        return true;
    }

    /*助力列表*/
    public static function helpList($user_id, $status = 0, $type = 1)
    {
        $field = 'id,id as progress_id,activity_id,jobs_id,grant_status,deadline_time,progress_type';
        $query = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', $type);
        if($status){
            $query->where('grant_status', $status);
        }
        $progress = $query->order('id desc')->paginate();
        if(!$progress->items()){
            return $progress;
        }
        foreach ($progress as $key => $value){
            $jobs = JobsModel::getJobsInfo($value->jobs_id);
            if($type == 2){
                $value->self_reward = [
                    'type' => $jobs->reward_method,
                    'point' => $jobs->reward_method == 1 ? (int)$jobs->reward_point : 0,
                    'youth' => $jobs->reward_method == 2 ? $jobs->youth_point : 0,
                    'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->reward_coupons_id)
                ];
            } else {
                $value->self_reward = [
                    'type' => $jobs->fu_reward_method,
                    'point' => $jobs->fu_reward_method == 1 ? (int)$jobs->fu_reward_point : 0,
                    'youth' => $jobs->fu_reward_method == 2 ? $jobs->fu_youth_point : 0,
                    'coupons' => MarketingCoupons::getAssociationCouponsOneArray($jobs->fu_reward_coupons_id)
                ];
            }
            $value->deadline_time = ($value->deadline_time - time());
            $value->grant_total = $jobs->grant_total;
            $value->difference = progressModel::getParticipateDifferenceUsers($value->id, $jobs->grant_total);
            $value->help_users_list = progressModel::getParticipateUsersList($value->id, $jobs->grant_total);
        }
        return $progress;
    }

    /*获取话题列表*/
    public static function getTalkLists($talk_id, $jobs, $progress = [])
    {
        if(!$talk_ids = XypHelper::formatJsonStringToArray($talk_id)){
            return [];
        }
        $field ='id as talk_id,title as talk_name';
        if(!$talk_lists = Huati::field($field)->where('id', 'in', $talk_ids)->select()){
            return [];
        }
        $progress_talk_ids = [];
        if(isset($progress->talk_id) && $progress->talk_id){
            $progress_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id);
        }
        foreach ($talk_lists as $key => $value){
            $talk_lists[$key]['total_limit'] = 1;
            $talk_lists[$key]['unique_id'] = '';
            $talk_lists[$key]['push_method'] = isset($jobs['push_method'])?$jobs['push_method']:0;
            $talk_lists[$key]['image_num'] = isset($jobs['image_num'])?$jobs['image_num']:0;
            $talk_lists[$key]['video_num'] = isset($jobs['video_num'])?$jobs['video_num']:0;
            $talk_lists[$key]['text_num'] = isset($jobs['text_num'])?$jobs['text_num']:0;
            if($progress && isset($progress['id'])){
                $talk_lists[$key]['unique_id'] = base64_encode($progress['id'].'_DynamicService_1');
                $talk_lists[$key]['status'] = ($progress_talk_ids && in_array($value->talk_id, $progress_talk_ids)) ? 2 : 0; // 0：未参与；1：审核中；2：已完成；3：审核失败；
            }
        }
        return $talk_lists;
    }

    /*获取话题列表*/
    public static function getInviteTalkLists($talk_id, $jobs, $progress = [])
    {
        if(!$talk_ids = XypHelper::formatJsonStringToArray($talk_id)){
            return [];
        }
        $field ='id as talk_id,title as talk_name';
        if(!$talk_lists = Huati::field($field)->where('id', 'in', $talk_ids)->select()){
            return [];
        }
        $progress_talk_ids = [];
        if(isset($progress->talk_id) && $progress->talk_id){
            $progress_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id);
        }
        foreach ($talk_lists as $key => $value){
            $talk_lists[$key]['total_limit'] = 1;
            $talk_lists[$key]['unique_id'] = '';
            $talk_lists[$key]['push_method'] = isset($jobs['push_method'])?$jobs['push_method']:0;
            $talk_lists[$key]['image_num'] = isset($jobs['image_num'])?$jobs['image_num']:0;
            $talk_lists[$key]['video_num'] = isset($jobs['video_num'])?$jobs['video_num']:0;
            $talk_lists[$key]['text_num'] = isset($jobs['text_num'])?$jobs['text_num']:0;
            if($progress && isset($progress['id'])){
                $talk_lists[$key]['unique_id'] = base64_encode($progress['id'].'_DynamicService_2');
                $talk_lists[$key]['status'] = ($progress_talk_ids && in_array($value->talk_id, $progress_talk_ids)) ? 2 : 0; // 0：未参与；1：审核中；2：已完成；3：审核失败；
            }
        }
        return $talk_lists;
    }

    public static function match($progress_id, $trends_id, $jobs_info){
        // 定义查询字段
        $fields = [
            'jobs' => 'id,activity_id,jobs_id,user_id,grant_status,deadline_time,talk_id,progress_type,trends_ids',
            'trends' => 'id,detail,images,mp4_file,huati_text,circle_id,user_id,goods_id,goods_title'
        ];

        $progress_type = ((isset($jobs_info['rules_key']) && $jobs_info['rules_key'] == 1)?1:2);
        $progress = progressModel::field($fields['jobs'])->where('id', $progress_id)->find();
        if (!$progress) {
            /*获取用户可参加的活动*/
            return ['status' => false, 'message' => 'Job not found'];
        }
        /*获取任务详情*/
        if (!$jobs = jobsModel::getJobsInfo($progress->jobs_id)) {
            return ['status' => false, 'msg' => '任务已结束，无法助力1'];
        }
        if(!$jobs_talk_ids = XypHelper::formatJsonStringToArray($jobs->talk_id)){
            return ['status' => false, 'msg' => '任务已结束，无法助力2'];
        }
        /*获取任务详情*/
        if (!$activity = ActivityModel::getActivityInfo($progress->activity_id)) {
            return ['status' => false, 'msg' => '任务已结束，无法助力3'];
        }
        if($activity->start_time > time() || $activity->end_time < time()){
            return ['status' => false, 'msg' => '任务已结束，无法助力4'];
        }
        if($activity->grant_status > 2){
            return ['status' => false, 'msg' => '任务已结束，无法助力5'];
        }
//        if($activity->grant_status == 2 && $activity->status_start_time){
//            if($activity->status_start_time > time()){
//                return ['status' => false, 'msg' => '任务未开始，无法助力6'];
//            }
//        }
        // 查询动态信息
        $trends = \app\common\model\Trends::field($fields['trends'])->where('id', $trends_id)->find();
        if (!$trends) {
            return ['status' => false, 'message' => 'Trends not found'];
        }
        $push_talk_ids = self::ProcessingTrendsTaskRules($jobs_talk_ids, $trends->huati_text);
        if(!$push_talk_ids){
            return ['status' => false, 'message' => '任务未开始，无法助力'];
        }
        if($talk_ids =  XypHelper::formatJsonStringToArray($progress->talk_id)){
            $push_talk_ids = array_unique(array_merge($talk_ids, $push_talk_ids));
        }
        $push_trends_ids = [];
        if($trends_ids =  XypHelper::formatJsonStringToArray($progress->trends_ids)){
            $push_trends_ids = array_push($trends_ids, $trends_id);
        }
        DB::startTrans();
        /*被邀请人参与动态任务*/
        if($progress_type == 2 && $progress->progress_type == 2){
            if((count($push_talk_ids) >= $jobs->push_num)){
                /*系统审核*/
                if($progress->examine_method == 1){
                    /*任务完成发放奖励,系统审核*/
                    if(!self::distributeRewardsInviter($progress->user_id, $jobs)){
                        DB::rollback();
                        return ['code' => 0, 'msg' => '任务已结束，无法助力'];
                    }
                    $progress->grant_status = 2;
                    $progress->complete_time = date('Y-m-d H:i:s');
                    $progress->examine_time = date('Y-m-d H:i:s');
                    $progress->receive_time = date('Y-m-d H:i:s');
                } else {
                    $progress->grant_status = 2;
                    $progress->complete_time = date('Y-m-d H:i:s');
                }
                $progress->talk_id = XypHelper::formatArrayToString($push_talk_ids);
                $progress->trends_ids = XypHelper::formatArrayToString($push_trends_ids);
                $progress->updatetime = time();
                $progress->save();
            } else {
                $progress->talk_id = XypHelper::formatArrayToString($push_talk_ids);
                $progress->trends_ids = XypHelper::formatArrayToString($push_trends_ids);
                $progress->updatetime = time();
                $progress->save();
            }
        } else {
            $dynamic_status = true;
            $invitation_status = true;
            if($jobs->dynamic_status == 1){
                $push_talk_ids = XypHelper::formatJsonStringToArray($progress->talk_id,'',[]);
                $dynamic_status = ((count($push_talk_ids) >= $jobs->push_num));
            }
            if($jobs->invitation_status == 1){
                $progress_total = progressModel::where('progress_id', $progress->id)->where('progress_type',2)->count();
                $invitation_status = ($progress_total >= $jobs->grant_total);
            }
            if($dynamic_status && $invitation_status && $jobs->examine_method == 1) {
                if(!self::distributeRewardsSelf($progress->user_id, $jobs)){
                    DB::rollback();
                    return ['code' => 0, 'msg' => '任务已结束，无法助力'];
                }
                progressModel::setProgressCompletion($progress_id, $push_talk_ids,$push_trends_ids);

            }else{
                $progress->talk_id = XypHelper::formatArrayToString($push_talk_ids);
                $progress->trends_ids = XypHelper::formatArrayToString($push_trends_ids);
                $progress->updatetime = time();
                $progress->save();
            }
        }
        $trends->ass_jobs_id = $progress->id;
        $trends->ass_jobs_source = 3;
        $trends->is_displayed = 2;
        $trends->save();
        DB::commit();
        return ['status' => true, 'msg' => '任务未开始，无法助力'];
    }

    /**
     * 处理动态任务规则
     *
     * 此函数用于判断动态是否符合给定的话题规则它检查动态是否绑定了特定的话题，
     * 如果绑定了，则根据动态的类型（如文本、图片等）进一步检查话题是否匹配
     * @param array $record_found       包含动态信息的数组，用于获取话题ID等信息
     * @param array $trends_talk_ids    一个包含有效话题ID的数组，用于匹配动态绑定的话题
     *
     * @return array
     */
    protected static function ProcessingTrendsTaskRules($jobs_talk_ids, $trends_talk_ids)
    {
        try {
            if (!$trends_talk = html_entity_decode($trends_talk_ids)) {
                return [];
            }
            $trends_talk = XypHelper::formatJsonStringToArray($trends_talk);
            // 动态未绑定话题，直接返回成功
            if (!($trends_talk) || !is_array($trends_talk)) {
                return [];
            }
            $trends_talk = array_values(array_filter(array_column($trends_talk, 'id')));
            if(!$trends_talk){
                return [];
            }
            return array_values(array_unique(array_intersect($jobs_talk_ids, $trends_talk)));
        } catch (\Exception $e) {
            return [];
        }
    }
}